import { View, Text, Image as TaroImage, } from '@tarojs/components'
import Taro, { useShareAppMessage } from '@tarojs/taro'
import TabBar from '../../components/tabbar'
import { NavBar, Image, Icon, Tab, Tabs, Swiper, SwiperItem, Grid, GridItem, NoticeBar, VirtualList, Tag, Button } from '@antmjs/vantui'
import { CusCard, CusSroll } from '../../components'
import { getMenuButtonBoundingClientRect } from '@tarojs/taro'
import { Ad } from '@tarojs/components'
import { IconFont } from '../../components'
import { useState, useEffect, useRef } from 'react'
import { GetAppList } from "../../https/home";
import { HOST, diffTime,getUserInfo,getRandomElements, judgeLogin } from '../../utils/const'
import './index.scss'

const pla = { android: "安卓", ios: "苹果", windows: "windows", mac: 'mac' }

export default function Home() {

  const [listData, setListData] = useState([])
  const virtualListRef = useRef();

  useEffect(() => {
    let rewardedVideoAd = null
    if (Taro.createInterstitialAd) {
      rewardedVideoAd = Taro.createInterstitialAd({ adUnitId: 'adunit-9faf42704df9f1eb', appSid: 'wx02e87e9d862d6304' })
      rewardedVideoAd.onLoad(() => {
        console.log('onLoad event emit')
      })
      rewardedVideoAd.onError((err) => {
        console.log('onError event emit', err)
      })
      rewardedVideoAd.onClose((res) => {
        console.log('onClose event emit', res)
      })

      rewardedVideoAd.show()
        .catch(() => {
          rewardedVideoAd.load()
            .then(() => rewardedVideoAd.show())
            .catch(err => {
              console.log('激励视频 广告显示失败')
            })
        })
    }
  }, [])

  useEffect(() => {
    getAPPList()
  }, [])

  const getAPPList = () => {
    Taro.showLoading('加载中')
    GetAppList().then((res) => {
      Taro.hideLoading()
      if (res.data.length > 0) {
        setListData(res.data)
      }
    })
  }

  useShareAppMessage((res) => {
    if (res.from === "button") {
      // 来自页面内分享按钮
    } else {
      // 右上角分享好友
    }

    return {
      title: "", // 分享卡片的title
      path: "", // 分享卡片的小程序路径
      imageUrl: "", // 分享卡片的图片链接
    };
  });

  const btn = getMenuButtonBoundingClientRect();

  const navView = () => {
    return (
      <View onClick={() => Taro.navigateTo({ url: '/pages/home/components/search_page/index' })} className='nav-search'>
        <Icon name='search' size={45} />
        <View className='text'>
          搜索全站应用
        </View>
      </View>
    )
  }

  return (
    <View className='home-view'>
      <NavBar
        title={navView()}
        fixed
        renderLeft={<Image
          round
          width="40px"
          onClick={() => {
            Taro.navigateTo({ url: '/pages/mine/components/mymaterial/index' })
          }}
          height="40px"
          src={getUserInfo()?.avatar?HOST+getUserInfo()?.avatar:"https://img.yzcdn.cn/vant/cat.jpeg"}
        />}
      />
      <View style={{ paddingTop: btn.bottom + 10 }} className='main-sub-box-view'>
        <View>
          <Swiper
            autoPlay={3000}
            height={260}
            className='top-cell'
            isCenter
          >
            {getRandomElements(listData, 8).map((item, index) => (
              <SwiperItem key={`swiper#demo5${index}`}  >
                <Image onClick={() => Taro.navigateTo({ url: `/pages/home/components/app_detail/index?id=${item.id}&version=${item.version}` })}
                  src={item?.icon ? HOST + item?.icon : ''} fit="fill" width="100%" height="260px" />
                <View
                  onClick={() => Taro.navigateTo({ url: `/pages/home/components/app_detail/index?id=${item.id}&version=${item.version}` })}
                  className='swiper-view'>
                  <Image src={item?.icon ? HOST + item?.icon : ''} radius={'8%'} width={120} height={120} />
                  <View className='info-view'>
                    <View>{item?.name}</View>
                    <View style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item?.desc}</View>
                  </View>
                  <View>
                    <Button onClick={() => Taro.navigateTo({ url: `/pages/home/components/down_load_file/index?link=${item?.link}` })} type='primary' size='small'>下载</Button>
                  </View>
                </View>
              </SwiperItem>
            ))}
          </Swiper>
        </View>
        <View className='top-cell'>
          <Grid columnNum={3}>
            <GridItem children={<View className='garid-bg'
              onClick={() => Taro.navigateTo({ url: '/pages/home/components/hot_app/index' })}>
              <IconFont name='ac-remen' size={70} />
              <View className='garid-text'>热门</View>
            </View>} />
            <GridItem onClick={() => {
              if(!judgeLogin()){
               return  Taro.showToast({title:'请先登录',icon:'error'})
              }
              Taro.navigateTo({ url: '/pages/home/components/everyday_sign_in/index' })
            }} children={<View className='garid-bg'>
              <IconFont name='ac-qiandao' size={70} />
              <View className='garid-text'>签到</View>
            </View>} />
            <GridItem children={<View className='garid-bg' onClick={() =>{
              if(!judgeLogin()){
                return  Taro.showToast({title:'请先登录',icon:'error'})
               }
               Taro.navigateTo({ url: '/pages/home/components/welfare/index' })
            }}>
              <IconFont name='ac-fuli' size={70} />
              <View className='garid-text'>福利</View>
            </View>} />
          </Grid>
        </View>
        <View className='ad-style'>
          <Ad
            unitId='adunit-8be2ebe74cd84b25'
            adIntervals={60}
            onLoad={() => console.log('ad onLoad')}
            onError={() => console.log('ad onError')}
            onClose={() => console.log('ad onClose')}
          />
        </View>
        <View className='top-cell'>
          <NoticeBar
            mode="link"
            style={{ backgroundColor: '#13b858' }}
            leftIcon="volume-o"
            text="易搜索应用全部规则已发布，建议各位同学阅读哦！"
          />
        </View>
        <View className='top-cell'>
          <CusCard headClick={() => Taro.navigateTo({ url: '/pages/home/components/app_version_list/index?type=1' })}
            top_left_tit={'新鲜出炉'} children={<CusSroll
              onClick={(item) => Taro.navigateTo({ url: `/pages/home/components/app_detail/index?id=${item.id}&version=${item.version}` })}
              btnClick={(item) => Taro.navigateTo({ url: `/pages/home/components/down_load_file/index?link=${item?.link}` })}
              type={'new-app'} scrollWidth={300} list={getRandomElements(listData, 10)} />} />
        </View>
        <View className='top-cell'>
          <CusCard
            headClick={() => Taro.navigateTo({ url: '/pages/home/components/app_version_list/index?type=2' })}
            top_left_tit={'好评如潮'} children={<CusSroll
              onClick={(item) => {
                Taro.navigateTo({ url: `/pages/home/components/app_detail/index?id=${item.id}&version=${item.version}` })
              }}
              btnClick={(item) => Taro.navigateTo({ url: `/pages/home/components/down_load_file/index?link=${item?.link}` })}
              type={'high-opinion'} list={getRandomElements(listData, 10)} />} />
        </View>
        <View className='top-cell'>
          <CusCard
            headClick={() => Taro.navigateTo({ url: '/pages/home/components/app_version_list/index?type=3' })}
            top_left_tit={'下载排行'}
            children={<CusSroll
              onClick={(item) => Taro.navigateTo({ url: `/pages/home/components/app_detail/index?id=${item.id}&version=${item.version}` })}
              type={'today-down'} list={getRandomElements(listData, 10)} />} />
        </View>
        <View className='ad-style'>
          <Ad
            unitId='adunit-e2bd846dc7f5d72d'
            adIntervals={60}
            onLoad={() => console.log('ad onLoad')}
            onError={() => console.log('ad onError')}
            onClose={() => console.log('ad onClose')}
          />
        </View>
        <View className='top-cell'>
          <CusCard
            headClick={() => Taro.navigateTo({ url: '/pages/home/components/app_version_list/index?type=3' })}
            top_left_tit={'今日下载榜'} />
          <View style={{ margin: '0 auto', width: '95%' }}>
            <VirtualList
              style={{ padding: 10, boxSizing: 'border-box' }}
              dataSource={getRandomElements(listData, 20)}
              showCount={300}
              ref={virtualListRef}
              ItemRender={({ item, index }) => {
                return (
                  <View className='list-main-view' style={{ marginTop: index == 0 ? 0 : 20 }}
                    onClick={() => Taro.navigateTo({ url: `/pages/home/components/app_detail/index?id=${item.id}&version=${item.version}` })}>
                    <TaroImage
                      className='home-list-view'
                      src={HOST + item?.icon}
                    />
                    <View className='list-cell-top-view' style={{ justifyContent: 'space-between' }}>
                      <View className="list-app-name-text">{item?.name}</View>
                      {item?.core && <View className="star-view">
                        <Icon name="star" color="#13b858" size={40} />
                        <Text className="star-text">{item?.core}</Text>
                      </View>}
                    </View>
                    <View className='list-info-view' style={{ justifyContent: 'space-between' }}>
                      <View className='list-sub-info-view'>
                        <View className='list-cell-top-view' style={{ marginTop: 5 }}>
                          <Tag type="primary">{item?.platform ? pla[item.platform] : ''}</Tag>
                          <View className="list-version-view">{item?.version}</View>
                        </View>
                        <View className='list-down-view'>{`今日${item?.downloadCnt || 0}次下载`}</View>
                      </View>
                      <View>
                        <Button onClick={() => Taro.navigateTo({ url: `/pages/home/components/down_load_file/index?link=${item?.link}` })}
                          type='primary' size='mini'>下载</Button>
                      </View>
                    </View>
                  </View>
                )
              }}
            />
          </View>
        </View>
      </View>
      <TabBar active={'home'} />
    </View>
  )
}
